<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="数据结构,算法,集合,">





  <link rel="alternate" href="/blog/atom.xml" title="编程那点事" type="application/atom+xml">






<meta name="description" content="学习JavaScript数据结构与算法（一）：栈与队列学习JavaScript数据结构与算法（二）：链表学习JavaScript数据结构与算法（三）：集合学习JavaScript数据结构与算法（四）：二叉搜索树  集合(Set)说起集合，就想起刚进高中时，数学第一课讲的就是集合。因此在学习集合这种数据结构时，倍感亲切。集合的基本性质有一条: 集合中元素是不重复的。因为这种性质，所以我们选用了对象">
<meta name="keywords" content="数据结构,算法,集合">
<meta property="og:type" content="article">
<meta property="og:title" content="学习JavaScript数据结构与算法（三）：集合">
<meta property="og:url" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（三）：集合/index.html">
<meta property="og:site_name" content="编程那点事">
<meta property="og:description" content="学习JavaScript数据结构与算法（一）：栈与队列学习JavaScript数据结构与算法（二）：链表学习JavaScript数据结构与算法（三）：集合学习JavaScript数据结构与算法（四）：二叉搜索树  集合(Set)说起集合，就想起刚进高中时，数学第一课讲的就是集合。因此在学习集合这种数据结构时，倍感亲切。集合的基本性质有一条: 集合中元素是不重复的。因为这种性质，所以我们选用了对象">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（三）：集合/set.png">
<meta property="og:updated_time" content="2019-10-03T05:53:45.948Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="学习JavaScript数据结构与算法（三）：集合">
<meta name="twitter:description" content="学习JavaScript数据结构与算法（一）：栈与队列学习JavaScript数据结构与算法（二）：链表学习JavaScript数据结构与算法（三）：集合学习JavaScript数据结构与算法（四）：二叉搜索树  集合(Set)说起集合，就想起刚进高中时，数学第一课讲的就是集合。因此在学习集合这种数据结构时，倍感亲切。集合的基本性质有一条: 集合中元素是不重复的。因为这种性质，所以我们选用了对象">
<meta name="twitter:image" content="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（三）：集合/set.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://lhweb.gitee.io/blog/2018/09/23/学习JavaScript数据结构与算法（三）：集合/">





  <title>学习JavaScript数据结构与算法（三）：集合 | 编程那点事</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">编程那点事</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://lhweb.gitee.io/blog/blog/2018/09/23/学习JavaScript数据结构与算法（三）：集合/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lhweb">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="编程那点事">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">学习JavaScript数据结构与算法（三）：集合</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-09-23T19:54:50+08:00">
                2018-09-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/javascript/" itemprop="url" rel="index">
                    <span itemprop="name">javascript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E6%A0%88%E4%B8%8E%E9%98%9F%E5%88%97/">学习JavaScript数据结构与算法（一）：栈与队列</a><br><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9A%E9%93%BE%E8%A1%A8/">学习JavaScript数据结构与算法（二）：链表</a><br><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E4%B8%89%EF%BC%89%EF%BC%9A%E9%9B%86%E5%90%88/">学习JavaScript数据结构与算法（三）：集合</a><br><a href="https://lhweb.gitee.io/blog/2018/09/23/%E5%AD%A6%E4%B9%A0JavaScript%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95%EF%BC%88%E5%9B%9B%EF%BC%89%EF%BC%9A%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91/">学习JavaScript数据结构与算法（四）：二叉搜索树</a></p>
</blockquote>
<h1 id="集合-Set"><a href="#集合-Set" class="headerlink" title="集合(Set)"></a>集合(Set)</h1><p>说起集合，就想起刚进高中时，数学第一课讲的就是集合。因此在学习集合这种数据结构时，倍感亲切。<br>集合的基本性质有一条: 集合中元素是不重复的。因为这种性质，所以我们选用了对象来作为集合的容器，而非数组。<br>虽然数组也能做到所有不重复，但终究过于繁琐，不如集合。</p>
<h2 id="集合的操作"><a href="#集合的操作" class="headerlink" title="集合的操作"></a>集合的操作</h2><p>集合的基本操作有交集、并集、差集等。这儿我们介绍JavaScipt集合中交集、并集、差集的实现。至于这三个的具体概念，可以看图:<br><img src="/blog/2018/09/23/学习JavaScript数据结构与算法（三）：集合/set.png" alt="交集、并集、差集"></p>
<h2 id="JavaScipt中集合的实现"><a href="#JavaScipt中集合的实现" class="headerlink" title="JavaScipt中集合的实现"></a>JavaScipt中集合的实现</h2><p>首先，创建一个构造函数。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 集合的构造函数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Set</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 集合元素的容器，以对象来表示</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@type</span> &#123;Object&#125;</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="keyword">var</span> items = &#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>集合需要有如下方法:</p>
<ul>
<li><p>has(value): 检测集合内是否有某个元素</p>
</li>
<li><p>add(value): 给集合内添加某个元素</p>
</li>
<li><p>remove(value): 移除集合中某个元素</p>
</li>
<li><p>clear(value): 清空集合</p>
</li>
<li><p>size(): 返回集合长度</p>
</li>
<li><p>values(): 返回集合转换的数组</p>
</li>
<li><p>union(otherSet): 返回两个集合的并集</p>
</li>
<li><p>intersection(otherSet): 返回两个集合的交集</p>
</li>
<li><p>difference(otherSet): 返回两个集合的差集</p>
</li>
<li><p>subset(otherSet): 判断该集合是否为传入集合的子集</p>
</li>
</ul>
<h3 id="has方法"><a href="#has方法" class="headerlink" title="has方法:"></a>has方法:</h3><p>说明:集合中元素是不重复的。所以在其它任何操作前，必须用has方法确认集合是否有某个元素。这儿使用了hasOwnProperty方法来检测。<br>实现:<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 检测集合内是否有某个元素</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span>  &#123;Any&#125;  value    要检测的元素</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &#123;Boolean&#125;       如果有，返回true</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">this.has = <span class="function"><span class="keyword">function</span><span class="params">(value)</span> </span>&#123;</span><br><span class="line">  <span class="comment">// hasOwnProperty的问题在于</span></span><br><span class="line">  <span class="comment">// 它是一个方法，所以可能会被覆写</span></span><br><span class="line">  <span class="keyword">return</span> items.hasOwnProperty(value)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="add方法"><a href="#add方法" class="headerlink" title="add方法:"></a>add方法:</h3><p>说明: 给集合内添加某个元素。<br>实现:<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 给集合内添加某个元素</span></span><br><span class="line"><span class="comment"> * @param &#123;Any&#125; value 要被添加的元素</span></span><br><span class="line"><span class="comment"> * @return &#123;Boolean&#125;       添加成功返回True。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.<span class="keyword">add</span> = function(<span class="keyword">value</span>) &#123;</span><br><span class="line">  <span class="comment">//先检测元素是否存在。</span></span><br><span class="line">  <span class="keyword">if</span> (!<span class="keyword">this</span>.has(<span class="keyword">value</span>)) &#123;</span><br><span class="line">    items[<span class="keyword">value</span>] = <span class="keyword">value</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//如果元素已存在则返回false</span></span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="remove方法"><a href="#remove方法" class="headerlink" title="remove方法:"></a>remove方法:</h3><p>说明: 移除集合中某个元素<br>实现:<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 移除集合中某个元素</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span>  &#123;Any&#125; value 要移除的元素</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &#123;Boolean&#125;       移除成功返回True。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.remove = function(value) &#123;</span><br><span class="line">  <span class="comment">//先检测元素是否存在。</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">this</span>.has(value)) &#123;</span><br><span class="line">    delete items[value];</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//如果元素不存在，则删除失败返回false</span></span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="clear方法"><a href="#clear方法" class="headerlink" title="clear方法:"></a>clear方法:</h3><p>说明: 清空集合<br>实现:<br><figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 清空集合</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.clear = <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.items = &#123;&#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="size方法"><a href="#size方法" class="headerlink" title="size方法"></a>size方法</h3><p>说明: 返回集合长度，这儿有两种方法。第一种方法使用了Object.keys这个Api，但只支持IE9及以上。第二种则适用于所有浏览器。<br>实现:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回集合长度，只可用于IE9及以上</span></span><br><span class="line"><span class="comment"> * @return &#123;Number&#125; 集合长度</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.size = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// Object.keys方法能将对象转化为数组</span></span><br><span class="line">  <span class="comment">// 只可用于IE9及以上，但很方便</span></span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Object</span>.keys(items).length;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回集合长度，可用于所有浏览器</span></span><br><span class="line"><span class="comment"> * @return &#123;Number&#125; 集合长度</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.sizeLegacy = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> prop <span class="keyword">in</span> items) &#123;</span><br><span class="line">    <span class="keyword">if</span> (items.hasOwnProperty(prop)) &#123;</span><br><span class="line">      ++count;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="values方法"><a href="#values方法" class="headerlink" title="values方法"></a>values方法</h3><p>说明: 返回集合转换的数组，这儿也有两种方法。理由同上。使用了Object.keys，只能支持IE9及以上。<br>实现:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回集合转换的数组，只可用于IE9及以上</span></span><br><span class="line"><span class="comment"> * @return &#123;Array&#125; 转换后的数组</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.values = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Object</span>.keys(items);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回集合转换的数组，可用于所有浏览器</span></span><br><span class="line"><span class="comment"> * @return &#123;Array&#125; 转换后的数组</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.valuesLegacy = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> keys = [];</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> items) &#123;</span><br><span class="line">    keys.push(key)</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> keys;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="union方法"><a href="#union方法" class="headerlink" title="union方法"></a>union方法</h3><p>说明: 返回两个集合的并集<br>实现:<br><figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回两个集合的并集</span></span><br><span class="line"><span class="comment"> * @param  &#123;Set&#125; otherSet 要进行并集操作的集合</span></span><br><span class="line"><span class="comment"> * @return &#123;Set&#125;          两个集合的并集</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">this.<span class="built_in">union</span> = function(otherSet) &#123;</span><br><span class="line">  //初始化一个新集合，用于表示并集。</span><br><span class="line">  <span class="built_in">var</span> unionSet = <span class="built_in">new</span> Set();</span><br><span class="line">  //将当前集合转换为数组，并依次添加进unionSet</span><br><span class="line">  <span class="built_in">var</span> <span class="built_in">values</span> = this.<span class="built_in">values</span>();</span><br><span class="line">  <span class="keyword">for</span> (<span class="built_in">var</span> i = <span class="number">0</span>; i &lt; <span class="built_in">values</span>.<span class="built_in">length</span>; i++) &#123;</span><br><span class="line">    unionSet.add(<span class="built_in">values</span>[i]);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  //将其它集合转换为数组，依次添加进unionSet。</span><br><span class="line">  //循环中的add方法保证了不会有重复元素的出现</span><br><span class="line">  <span class="built_in">values</span> = otherSet.<span class="built_in">values</span>();</span><br><span class="line">  <span class="keyword">for</span> (<span class="built_in">var</span> i = <span class="number">0</span>; i &lt; <span class="built_in">values</span>.<span class="built_in">length</span>; i++) &#123;</span><br><span class="line">    unionSet.add(<span class="built_in">values</span>[i]);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">return</span> unionSet;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="intersection方法"><a href="#intersection方法" class="headerlink" title="intersection方法"></a>intersection方法</h3><p>说明: 返回两个集合的交集<br>实现:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回两个集合的交集</span></span><br><span class="line"><span class="comment"> * @param  &#123;Set&#125; otherSet 要进行交集操作的集合</span></span><br><span class="line"><span class="comment"> * @return &#123;Set&#125;          两个集合的交集</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.intersection = <span class="function"><span class="keyword">function</span>(<span class="params">otherSet</span>) </span>&#123;</span><br><span class="line">  <span class="comment">//初始化一个新集合，用于表示交集。</span></span><br><span class="line">  <span class="keyword">var</span> interSectionSet = <span class="keyword">new</span> <span class="built_in">Set</span>();</span><br><span class="line">  <span class="comment">//将当前集合转换为数组</span></span><br><span class="line">  <span class="keyword">var</span> values = <span class="keyword">this</span>.values();</span><br><span class="line">  <span class="comment">//遍历数组，如果另外一个集合也有该元素，则interSectionSet加入该元素。</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (otherSet.has(values[i])) &#123;</span><br><span class="line">      interSectionSet.add(values[i])</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> interSectionSet;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="difference方法"><a href="#difference方法" class="headerlink" title="difference方法"></a>difference方法</h3><p>说明: 返回两个集合的差集<br>实现:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回两个集合的差集</span></span><br><span class="line"><span class="comment"> * @param  &#123;Set&#125; otherSet 要进行差集操作的集合</span></span><br><span class="line"><span class="comment"> * @return &#123;Set&#125;          两个集合的差集</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.difference = <span class="function"><span class="keyword">function</span>(<span class="params">otherSet</span>) </span>&#123;</span><br><span class="line">  <span class="comment">//初始化一个新集合，用于表示差集。</span></span><br><span class="line">  <span class="keyword">var</span> differenceSet = <span class="keyword">new</span> <span class="built_in">Set</span>();</span><br><span class="line">  <span class="comment">//将当前集合转换为数组</span></span><br><span class="line">  <span class="keyword">var</span> values = <span class="keyword">this</span>.values();</span><br><span class="line">  <span class="comment">//遍历数组，如果另外一个集合没有该元素，则differenceSet加入该元素。</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!otherSet.has(values[i])) &#123;</span><br><span class="line">      differenceSet.add(values[i])</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> differenceSet;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h3 id="subset方法"><a href="#subset方法" class="headerlink" title="subset方法"></a>subset方法</h3><p>说明: 判断该集合是否为传入集合的子集。这段代码在我自己写完后与书上一比对，觉得自己超级low。我写的要遍历数组三次，书上的只需要一次，算法复杂度远远低于我的。<br>实现:<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 判断该集合是否为传入集合的子集</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span>  &#123;Set&#125; otherSet 传入的集合</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &#123;Boolean&#125;      是则返回True</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">this</span>.subset = function(otherSet) &#123;</span><br><span class="line">  <span class="comment">// 第一个判定,如果该集合长度大于otherSet的长度</span></span><br><span class="line">  <span class="comment">// 则直接返回false</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">this</span>.size() &gt; otherSet.size()) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 将当前集合转换为数组</span></span><br><span class="line">    <span class="keyword">var</span> values = <span class="keyword">this</span>.values();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (!otherSet.has(values[i])) &#123;</span><br><span class="line">        <span class="comment">// 第二个判定。只要有一个元素不在otherSet中</span></span><br><span class="line">        <span class="comment">// 那么则可以直接判定不是子集，返回false</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<h1 id="ES6中的集合"><a href="#ES6中的集合" class="headerlink" title="ES6中的集合"></a>ES6中的集合</h1><p>ES6也提供了集合，但之前看ES6的集合操作一直迷迷糊糊的。实现一遍后再去看，感觉概念清晰了很多。<br>具体的我掌握的不是很好，还在学习中，就不写出来啦~推荐看阮一峰老师的《ECMAScript 6入门》中对ES6 Set的介绍。</p>
<p><a href="http://es6.ruanyifeng.com/#docs/set-map#WeakSet" target="_blank" rel="noopener">《ECMAScript 6入门》– Set和Map数据结构</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/数据结构/" rel="tag"># 数据结构</a>
          
            <a href="/blog/tags/算法/" rel="tag"># 算法</a>
          
            <a href="/blog/tags/集合/" rel="tag"># 集合</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/09/23/学习JavaScript数据结构与算法（二）：链表/" rel="next" title="学习JavaScript数据结构与算法（二）：链表">
                <i class="fa fa-chevron-left"></i> 学习JavaScript数据结构与算法（二）：链表
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/09/23/学习JavaScript数据结构与算法（四）：二叉搜索树/" rel="prev" title="学习JavaScript数据结构与算法（四）：二叉搜索树">
                学习JavaScript数据结构与算法（四）：二叉搜索树 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">lhweb</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#集合-Set"><span class="nav-number">1.</span> <span class="nav-text">集合(Set)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#集合的操作"><span class="nav-number">1.1.</span> <span class="nav-text">集合的操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JavaScipt中集合的实现"><span class="nav-number">1.2.</span> <span class="nav-text">JavaScipt中集合的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#has方法"><span class="nav-number">1.2.1.</span> <span class="nav-text">has方法:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#add方法"><span class="nav-number">1.2.2.</span> <span class="nav-text">add方法:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#remove方法"><span class="nav-number">1.2.3.</span> <span class="nav-text">remove方法:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#clear方法"><span class="nav-number">1.2.4.</span> <span class="nav-text">clear方法:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#size方法"><span class="nav-number">1.2.5.</span> <span class="nav-text">size方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#values方法"><span class="nav-number">1.2.6.</span> <span class="nav-text">values方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#union方法"><span class="nav-number">1.2.7.</span> <span class="nav-text">union方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#intersection方法"><span class="nav-number">1.2.8.</span> <span class="nav-text">intersection方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#difference方法"><span class="nav-number">1.2.9.</span> <span class="nav-text">difference方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#subset方法"><span class="nav-number">1.2.10.</span> <span class="nav-text">subset方法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ES6中的集合"><span class="nav-number">2.</span> <span class="nav-text">ES6中的集合</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lhweb</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
